package cn.kgc.vue.controller;

import cn.hutool.core.util.RandomUtil;
import cn.kgc.vue.annotatios.LogOperation;
import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.entity.User;
import cn.kgc.vue.enums.OperationType;
import cn.kgc.vue.form.UserForm;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.response.ResponseStatus;
import cn.kgc.vue.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/9/20
 * @description 在项目开发过程中 需要对项目进行调试 需要输出一些数据信息
 * 方案:
 * 1.System.out.println()    不便于信息的维护
 * 2. log   日志信息打印     调整日志的打印级别  实现日志是打印还是不打印   便于信息维护
 * <p>
 * debug  info  warn  error
 * <p>
 * 全局设置
 * debug    debug  info  warn  error
 * info     info  warn  error
 * warn     warn  error
 * error    error
 */
@RestController
@RequestMapping("user")
// @CrossOrigin
@Slf4j
@Tag(name = "用户模块")
public class UserController {

    @Resource
    private UserService userService;

    // 获取用户权限菜单
    @GetMapping("/menu")
    public ResponseResult  userMenu(HttpServletRequest request){
        return  userService.menuList(request);
    }

    // 修改个人密码
    @Operation(summary = "修改密码")
    @PutMapping("editPersonalPassword")
    @Parameters({
            @Parameter(name = "params",description = "个人信息参数"),
            @Parameter(name = "request",description = "请求对象",required = true),
    })
    public ResponseResult editPersonalPassword(@RequestBody Map<String,String> params,HttpServletRequest request){
        return userService.editPersonalPassword(params,request);
    }

    // 编辑用户个人信息
    @PutMapping("editPersonalInfo")
    @LogOperation(model = "用户模块",operation = OperationType.UPDATE)
    public ResponseResult editPersonalInfo(@RequestBody UserForm userForm){
        return userService.editPersonalInfo(userForm);
    }

    // 获取用户个人信息
    @GetMapping("personalInfo")
    public ResponseResult getPersonalInfo(HttpServletRequest request){
        return userService.getPersonalInfo(request);
    }

    // 批量删除
    @DeleteMapping("batchDelete")
    @RequiresPermissions("sys:user:delete")
    public  ResponseResult  batchDelete(@RequestBody List<Integer> ids){
        return  userService.batchDelete(ids);
    }

    // 重置用户密码
    @PutMapping("resetPassword/{id}")
    @RequiresPermissions("sys:user:pwd")
    @LogOperation(model = "用户模块",operation = OperationType.UPDATE)
    public ResponseResult resetPassword(@PathVariable("id")Integer id){

        User user = new User();
        String salt = RandomUtil.randomString(8);
        String defaultPwd = "123456";
        user.setSalt(salt);
        user.setPassword(new SimpleHash("MD5",defaultPwd,salt,10).toHex());

        userService.updateById(user);

        return  ResponseResult.success().message("密码重置成功");
    }



    // 编辑用户状态
    @PutMapping("state/{id}/{state}")
    @RequiresPermissions("sys:user:state")
    @LogOperation(model = "用户模块",operation = OperationType.UPDATE)
    public ResponseResult editUserState( @PathVariable("id") Integer id,@PathVariable("state") Integer state){
        User user = new User();
        user.setState(state);
        user.setId(id);
        userService.updateById(user);
        return  ResponseResult.success();
    }


    // 添加用户
    @PostMapping("add")
    @RequiresPermissions("sys:user:add")
    public ResponseResult addUser(@RequestBody UserForm userForm) {
        log.debug("info={}",userForm.getUsername());
        return userService.addUser(userForm);
    }

    // 编辑用户
    @PutMapping("edit")
    @RequiresPermissions("sys:user:update")
    public ResponseResult editUser(@RequestBody UserForm userForm) {
        log.debug("info={},version={}",userForm.getUsername(),userForm.getVersion());
        return userService.editUser(userForm);
    }

    // 用户信息分页
    @PostMapping("page")
    public ResponseResult userPage(@RequestBody QueryCondition<User> queryCondition) {
        log.debug("pageParams={}", queryCondition);
        return userService.userPage(queryCondition);
    }


    // 认证接口
    @PostMapping("login")
    public ResponseResult login(@RequestBody HashMap<String, Object> params, HttpServletRequest request) {
        log.debug("params={}", params);
        return userService.login(params, request);
    }


    // 退出登录
    @GetMapping("logout")
    public ResponseResult logout(HttpServletRequest request) {
        return userService.logout(request);
    }


    /*
     * 该接口允许跨域访问
     *   http://localhost:8080   源
     *   http://localhost:9090/kgc/user/captcha  目标
     *
     *  浏览器中位了保证请求的安全性   同源策略
     *   请求协议:  http     https
     *   请求地址  192.168.253.135    192.168.253.133
     *  请求接口  8080    9090
     *
     *   跨域  违背了浏览器中的同源策略  只要以上三个方面其中之一不一样 则出现跨域问题
     *
     *   处理跨域问题
     *    1.后端处理
     *        1.1  局部处理方案  在需要允许跨域的接口或类上添加 @CrossOrigin
     *        1.2  全局处理跨域问题  通过配置类实现
     *    2.前端处理
     * */
    // @CrossOrigin
    // 获取验证码接口
    @GetMapping("captcha")
    public ResponseResult createCaptcha() {

        return userService.createCaptcha();
    }

    /*未认证的请求  跳转的路径*/
    @GetMapping("unAuth")
    public ResponseResult unAuth() {
        return ResponseResult.fail()
                .code(ResponseStatus.UN_AUTH)
                .message(ResponseStatus.UN_AUTH.getMessage());
    }

}
